<template>
  <div class="wrap" ref="scrollRef" >
    <div class="list-item"
      v-for="item of dataList"
      :key="item.id">
          {{ item.content }}
    </div>

    <div  class="bottom-box" >
      <span v-if="!noData">- Loading -</span>
      <span v-else-if="noData">- No Data -</span>
    </div>
  </div>
    
</template>

<script>
// 引入loadsh可以使用防抖函数
import _ from 'loadsh';

export default {
  name: 'MyList',
  props: ['data', 'pageCount'],
  data() {
    return {
      dataList: [],
      startIndex:0,
      noData:false
    }
  },
  mounted() {
    
    this.oScrollRef = this.$refs.scrollRef;
    // this.oScrollRef = document.getElementsByClassName('wrap')[0]; 使用这种方式也是可以的
    
    //_.debounce(this.loadMore,300)   防抖
    this.oScrollRef.addEventListener('scroll', _.debounce(this.loadMore, 300), false);
    this.setDataList();
  },
  methods: {
    setDataList() {
      if (this.startIndex > this.data.length - 1) {
        this.noData = true;
        return;
      }

        this.dataList.push(...this.data.slice(
          this.startIndex, this.startIndex += this.pageCount
        ));
    },
    loadMore() {
      const oScroll = this.oScrollRef;

      const listHeight = oScroll.clientHeight;
      const scrollHeight = oScroll.scrollHeight;
      const scrollTop = oScroll.scrollTop;

      if (listHeight + scrollTop >= scrollHeight - 10) {
        this.setDataList();
      }
    }
  }
}
</script>

<style>
.wrap {
  height: 844px;
  width: 100%;
  /* 在vue的子组件中必须设置 overflow: scroll，这样才可以监听到scroll事件
    若没有设置的话，就会监听不到
  */
  overflow: scroll;
}

.list-item {
  width: 100%;
  height: 200px;
  text-align: center;
  line-height: 200px;
  font-size: 30px;
}

.bottom-box {
  width: 100%;
  height: 44px;
  text-align: center;
  line-height: 44px;
  font-size: 20px;
}
</style>